//
//  LNHConfirmOrderViewController.m
//  LNH
//
//  Created by cruise on 2018/2/14.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "LNHConfirmOrderViewController.h"
#import "LNHConfirmOrderViewModel.h"
#import "LNHConfirmOrderCell0.h"
#import "LNHConfirmOrderCell.h"
#import "LNHConfirmOrderHeaderView.h"
#import "CAAddressViewController.h"
#import "CAPaymentView.h"
#import "CASubmitOrderApi.h"
#import "CAPayOrderApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APOrderInfo.h"
#import "CASubmitOrderNoCartApi.h"
#import "CAUpgradeSubmitNoCartApi.h"

@interface LNHConfirmOrderViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, CAAddressViewControllerDelegate> {
    NSString *_remark;
    NSString *_addressId;
    NSString *_orderId;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) LNHConfirmOrderViewModel *viewModel;

@property (nonatomic, strong) LNHConfirmOrderHeaderView *headerView;

@property (nonatomic, strong) CAPaymentView *paymentView;

@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UIButton *submitButton;

@end

@implementation LNHConfirmOrderViewController

/// 初始化数据
- (void)lm_initialDefaultsForController{
    [self setViewModel:[[LNHConfirmOrderViewModel alloc] initWithParams:self.params]];
}

/// 绑定 vm
- (void)lm_bindViewModelForController{
    @weakify(self);
    
    [self.viewModel.fetchconfirmDataCommand execute:nil];
    
    [[RACObserve(self.viewModel, dataList) filter:^BOOL(NSArray *list) {
        return list.count > 0;
    }] subscribeNext:^(NSArray *list) {
        [self.tableView reloadData];
    }];
    
    // 监听取商品详细信号是否在执行
    [[self.viewModel.fetchconfirmDataCommand.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
        @strongify(self);
        
        if (x.boolValue) {
            [MBProgressHUD showActivityIndicatorWithTip:@"加载中..."];
        }else {
            [MBProgressHUD hideHUD];
        }
    }];
    
    [[RACObserve(self.viewModel, paymentStr) filter:^BOOL(id  _Nullable value) {
        return value;
    }] subscribeNext:^(id  _Nullable x) {
        [self.priceLabel setText:[NSString stringWithFormat:@"合计金额：%@", self.viewModel.paymentStr]];
        [self.paymentView.priceLabel setText:[NSString stringWithFormat:@"%@", self.viewModel.paymentStr]];
    }];
    
    [[RACObserve(self.viewModel, addressDict) filter:^BOOL(id  _Nullable value) {
        return value;
    }] subscribeNext:^(id  _Nullable x) {
        _addressId = [NSString stringWithFormat:@"%ld", [self.viewModel.addressDict[@"id"] integerValue]];
    }];
    
}

/// 创建视图
- (void)lm_createViewForController{
    
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.priceLabel];
    [self.view addSubview:self.submitButton];
    [self.view addSubview:self.paymentView];
    
    [self.view setNeedsUpdateConstraints];
}

/// 配置导航栏
- (void)lm_configNavigationForController{
    self.title = @"确认订单";
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = RGBCOLOR(113, 113, 113);
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : RGBCOLOR(35, 24, 21), NSFontAttributeName : [UIFont systemFontOfSize:16]};
    _remark = @"";
}

#pragma mark - Layout

- (void)updateViewConstraints
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.priceLabel.mas_top);
    }];
    
    [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(150, 40));
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(isIPhoneX ? -34 : 0);
    }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(40);
        make.left.equalTo(self.view);
        make.right.equalTo(self.submitButton.mas_left).offset(-20);
        make.bottom.equalTo(self.view).offset(isIPhoneX ? -34 : 0);
    }];
    
//    [self.paymentView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.and.right.equalTo(self.view);
//        make.bottom.equalTo(self.view);
//        make.height.mas_equalTo(SCREEN_HEIGHT * 0.6);
//    }];
    
    [super updateViewConstraints];
}

-(UITableView *) tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        
        [_tableView setRowHeight:UITableViewAutomaticDimension];
        [_tableView setEstimatedRowHeight:80];
        
        [_tableView setTableHeaderView:self.headerView];
        [_tableView setTableFooterView:[UIView new]];
    }
    return _tableView;
}

-(LNHConfirmOrderHeaderView *) headerView {
    if (!_headerView) {
        _headerView = [[LNHConfirmOrderHeaderView alloc] initWithFrame:(CGRect){ 0, 0, SCREEN_WIDTH, 80 }];
        [_headerView bindViewModel:self.viewModel withParams:nil];
        
        UITapGestureRecognizer *gesture = [UITapGestureRecognizer new];
        [self.headerView addGestureRecognizer:gesture];
        
        [[gesture rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            CAAddressViewController *addressVC = [CAAddressViewController new];
            addressVC.delegate = self;
            [self.navigationController pushViewController:addressVC animated:YES];
        }];
    }
    return _headerView;
}

-(UILabel *) priceLabel {
    if (!_priceLabel) {
        _priceLabel = [UILabel new];
        [_priceLabel setTextColor:RGBCOLOR(113,112,113)];
        [_priceLabel setFont:[UIFont systemFontOfSize:14]];
        [_priceLabel setTextAlignment:NSTextAlignmentRight];
    }
    return _priceLabel;
}

-(UIButton *) submitButton {
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitButton setTitle:@"提交订单" forState:UIControlStateNormal];
        [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_submitButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
        [_submitButton setBackgroundColor:RGBCOLOR(233, 85, 19)];
        
        [[_submitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self showPayView];
        }];
    }
    return _submitButton;
}

- (CAPaymentView *)paymentView {
    if (!_paymentView) {
        _paymentView = [CAPaymentView new];
        _paymentView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT * 0.6);
        _paymentView.userInteractionEnabled = YES;
        [[_paymentView.closeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self hidePayView];
        }];
        
        [[_paymentView.payButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self createOrder];
        }];
    }
    return _paymentView;
}

#pragma mark private method
- (void) showPayView {
//    _paymentView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT * 0.6);
    [UIView animateWithDuration:0.3 animations:^{
        if (isIPhoneX) {
            _paymentView.frame = CGRectMake(0, SCREEN_HEIGHT - SCREEN_HEIGHT * 0.6 - 88, SCREEN_WIDTH, SCREEN_HEIGHT * 0.6);
        } else {
            _paymentView.frame = CGRectMake(0, SCREEN_HEIGHT - SCREEN_HEIGHT * 0.6 - 54, SCREEN_WIDTH, SCREEN_HEIGHT * 0.6);
        }
    }];
}

- (void) hidePayView {
    [UIView animateWithDuration:0.3 animations:^{
        _paymentView.transform = CGAffineTransformTranslate(_paymentView.transform, 0, SCREEN_HEIGHT * 0.6);
    }];
}

- (void) createOrder {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if (self.viewModel.levelId != nil && ![self.viewModel.levelId isEqualToString:@""]) {
        NSLog(@"%@", self.params);
        CAUpgradeSubmitNoCartApi *upgradeSubmitOrderApi = [[CAUpgradeSubmitNoCartApi alloc] initGoodsId:self.params[@"goodsId"] Sku:self.params[@"sku"] Level:self.params[@"level"] DistrictId:self.params[@"districtId"] == nil ? @"":self.params[@"districtId"] InviteCode:self.params[@"inviteCode"] == nil ? @"":self.params[@"inviteCode"] AddressId:_addressId Remark:_remark];
        [upgradeSubmitOrderApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            CAUpgradeSubmitNoCartApi *api = (CAUpgradeSubmitNoCartApi *) request;
            if (api.done) {
                _orderId = api.responseObject[@"result"][@"id"];
                [self alipayPay];
            } else {
                [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
        }];
    } else if (self.viewModel.cartIds != nil) {
        CASubmitOrderApi *submitOrderApi = [[CASubmitOrderApi alloc] initCartIds:self.params[@"cartIds"] AddressId:_addressId Remark:_remark];
        [submitOrderApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            CASubmitOrderApi *api = (CASubmitOrderApi *) request;
            if (api.done) {
                _orderId = api.responseObject[@"result"][@"id"];
                [self alipayPay];
            } else {
                [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
        }];
    } else {
        CASubmitOrderNoCartApi *submitOrderApi = [[CASubmitOrderNoCartApi alloc] initGoodsId:self.params[@"goodsId"] Sku:self.params[@"sku"] Number:self.params[@"number"] AddressId:_addressId Remark:_remark];
        [submitOrderApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            CASubmitOrderNoCartApi *api = (CASubmitOrderNoCartApi *) request;
            if (api.done) {
                _orderId = api.responseObject[@"result"][@"id"];
                [self alipayPay];
            } else {
                [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
        }];
    }
}

- (void) alipayPay {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    CAPayOrderApi *payOrderApi = [[CAPayOrderApi alloc] initOrderId:_orderId Payment:@"alipay"];
    [payOrderApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CAPayOrderApi *api = (CAPayOrderApi *) request;
        if (api.done) {
//            APOrderInfo *orderInfo = [APOrderInfo new];
//            orderInfo.app_id = api.responseObject[@"result"][@"pay"][@"app_id"];
//            orderInfo.method = api.responseObject[@"result"][@"pay"][@"method"];
//            orderInfo.format = api.responseObject[@"result"][@"pay"][@"format"];
//            orderInfo.charset = api.responseObject[@"result"][@"pay"][@"charset"];
//            orderInfo.sign_type = api.responseObject[@"result"][@"pay"][@"sign_type"];
//            orderInfo.timestamp = api.responseObject[@"result"][@"pay"][@"timestamp"];
//            orderInfo.version = api.responseObject[@"result"][@"pay"][@"version"];
//            orderInfo.notify_url = api.responseObject[@"result"][@"pay"][@"notify_url"];
//
////            NSDictionary *bizDict = api.responseObject[@"result"][@"pay"][@"biz_content"];
//            NSData *stringData = [api.responseObject[@"result"][@"pay"][@"biz_content"] dataUsingEncoding:NSUTF8StringEncoding];
//            NSDictionary *bizDict = [NSJSONSerialization JSONObjectWithData:stringData options:0 error:nil];
//            orderInfo.biz_content = [APBizContent new];
//            orderInfo.biz_content.body = bizDict[@"body"];
//            orderInfo.biz_content.subject = bizDict[@"subject"];
//            orderInfo.biz_content.out_trade_no = bizDict[@"out_trade_no"];
//            orderInfo.biz_content.timeout_express = bizDict[@"timeout_express"];
//            orderInfo.biz_content.total_amount = bizDict[@"total_amount"];
//            orderInfo.biz_content.product_code = bizDict[@"product_code"];
////            orderInfo.biz_content.seller_id = @"383590449@qq.com";
//
//            NSString *signedString = api.responseObject[@"result"][@"pay"][@"sign"];
//            NSString *orderInfoEncoded = [orderInfo orderInfoEncoded:NO];
//            NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
//                                     orderInfoEncoded, signedString];
            [[AlipaySDK defaultService] payOrder:api.responseObject[@"result"][@"pay"] fromScheme:@"LNH" callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
            }];
            
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma - mark UITableViewDelegate & UITableViewDataSource

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.viewModel.dataList.count + 3;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row >= self.viewModel.dataList.count) {
        
        LNHConfirmOrderCell0 *cell = [tableView dequeueReusableCellWithIdentifier:GCN(LNHConfirmOrderCell0)];
        
        if (cell == nil) {
            cell = [[LNHConfirmOrderCell0 alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:GCN(LNHConfirmOrderCell0)];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (self.viewModel.dataList.count == indexPath.row) {
            //备注
            [cell.titleLabel setText:@"备注:"];
//            [cell.contentLabel setText:self.viewModel.remarkStr];
            cell.contentTextField.hidden = NO;
            cell.contentLabel.hidden = YES;
            cell.contentTextField.delegate = self;
            
        } else if (self.viewModel.dataList.count+1 == indexPath.row) {
            //运费
            [cell.titleLabel setText:@"运费:"];
            [cell.contentLabel setText:self.viewModel.shippingStr];
        } else if (self.viewModel.dataList.count+2 == indexPath.row){
            //实付款
            [cell.titleLabel setText:@"实付款(含运费):"];
            [cell.contentLabel setText:self.viewModel.paymentStr];
        }
        
        return cell;
        
    } else {
        LNHConfirmOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:GCN(LNHConfirmOrderCell)];
        
        if (cell == nil) {
            cell = [[LNHConfirmOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:GCN(LNHConfirmOrderCell)];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSDictionary *dict =self.viewModel.dataList[indexPath.row];
        
        [cell.goodsImageView setImage:LMImageNamed(dict[@"image"])];
        [cell.goodsImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, dict[@"goods_img"]]]];
        [cell.nameLabel setText:dict[@"name"]];
        [cell.priceLabel setText:dict[@"price"]];
        [cell.numLabel setText:[NSString stringWithFormat:@"x%ld", [dict[@"number"] integerValue]]];
        
        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.viewModel.dataList.count) {
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
    } else {
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, SCREEN_WIDTH)];
        }
    }
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    _remark = textField.text;
}

#pragma mark Address Delegate
-(void) selectAddressWithDict:(NSDictionary *) dict {
    self.viewModel.addressDict = dict;
}

@end
